<template>
    <el-drawer
        ref="drawRef"
        class="reset"
        v-model="dialogVisible"
        :title="'新增长期保报案'"
        :destroy-on-close="true"
        @close="handleClose"
        :size="isMobile ? '100%' : 750"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
    >
        <div class="w-full box-border p-16px">
            <el-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-position="top"
                class=""
            >
                <div class="grid gap-10px">
                    <el-form-item
                        :class="[i.width]"
                        v-for="(i, index) in formData"
                        :key="index"
                        :label="i.label"
                        :prop="`${i.prop}.value`"
                    >
                        <el-select
                            v-if="i.type === 'select'"
                            class="w-full"
                            v-model="i.value"
                            :filterable="i.filterable"
                            :remote="i.remote"
                            :placeholder="i.placeholder"
                            :disabled="i.disabled"
                            :remote-method="($event) => i.remoteMethod($event, i)"
                            @focus="i.focus && i.focus(i)"
                            @change="i.change && i.change(i)"
                        >
                            <el-option
                                v-for="item in i.options"
                                :key="item[i.defaultAttrs.value]"
                                :label="item[i.defaultAttrs.label]"
                                :value="item[i.defaultAttrs.value]"
                            />
                        </el-select>

                        <el-date-picker
                            v-if="i.type === 'date'"
                            class="reset-date w-full"
                            v-model="i.value"
                            :type="i.dateType || 'date'"
                            :value-format="i.valueFormat || 'YYYY-MM-DD'"
                            :placeholder="i.placeholder"
                            :disabled-date="i.disabledDate && i.disabledDate"
                            @focus="i.focus && i.focus(i)"
                            @change="i.focus && i.focus(i)"
                        />

                        <el-input
                            v-if="i.type === 'input'"
                            class="w-full"
                            v-model="i.value"
                            :placeholder="i.placeholder"
                        />

                        <el-input
                            v-if="i.type === 'textarea'"
                            class="w-full"
                            v-model="i.value"
                            :maxlength="i.maxlength || 500"
                            :placeholder="i.placeholder"
                            show-word-limit
                            type="textarea"
                        />
                        <uploadVideo v-if="i.type === 'upload'" v-model="i.value" />
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <template #footer>
            <div class="flex flex-jc-c">
                <el-button type="primary" plain @click="submit">提交</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { cloneDeep } from 'lodash'
import uploadImage from '@/components/uploadImage/index.vue'
import uploadVideo from '@/components/uploadVideo/index.vue'
import {
    getoutdangerliststaffapi,
    reportlongcaseapi,
} from '@/api/reportClaimAdjuster/addLongCase.ts'
import { getCompanyByName } from '@/api/tools/blackList.ts'
import { useStore } from '@/store/index.ts'
import { dayjs, ElMessage } from 'element-plus'
const store = useStore()
const drawRef = ref(null)
const isMobile = ref(window.isMobile)

const formRef = ref(null)
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

const previewList = ref([])

const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    curItem: {
        type: Object,
    },
    insureType: {
        type: String,
    },
})

const emits = defineEmits(['update:show', 'success'])

const dialogVisible = ref(false)

const formData = ref({
    company: {
        label: '报案公司',
        prop: 'company',
        type: 'select',
        placeholder: '请输入报案公司名称',
        value: '',
        filterable: true,
        remote: true,
        remoteMethod: (ev, item) => {
            if (!ev) return
            getCompanyByName({
                auditStatus: 1,
                companyName: ev,
            }).then((res) => {
                item.options = res || []
                item.options.forEach((i) => {
                    i.companyName = i.superAdminUserName
                        ? i.companyName + `(${i.superAdminUserName})`
                        : i.companyName
                })
            })
        },
        options: [],
        defaultAttrs: {
            label: 'companyName',
            value: 'id',
        },
        width: 'full',
        change: () => {
            formData.value.people.value = ''
            formData.value.people.options = []
            formData.value.phone.value = ''
            formData.value.caseDate.value = ''
        },
    },
    videos: {
        label: '上传受伤者视频',
        prop: 'videos',
        type: 'upload',
        value: '',
        width: 'full',
    },
    people: {
        label: '出险人',
        type: 'select',
        prop: 'people',
        placeholder: '请选择出险人',
        value: '',
        value1: '',
        options: [],
        defaultAttrs: {
            label: 'outDangerUserName',
            value: 'id',
        },
        width: 'half',
        tbtade: '',
        filterable: true,
        remote: true,
        remoteMethod: (ev, item) => {
            if (!ev) return
            getoutdangerliststaffapi({
                companyId: formData.value.company.value,
                searchUserInfo: ev,
                isAdmin: 1,
            }).then((res) => {
                console.log(res)
                item.options = res.list || []
                item.options.forEach((i) => {
                    i.outDangerUserName =
                        i.userName +
                        '（' +
                        i?.idCardNo?.substring(14) +
                        '）' +
                        '投保时间:' +
                        i.insurStartTime
                })
            })
        },
        focus: (i) => {
            if (!formData.value.company.value) {
                ElMessage({
                    message: '请先选择公司',
                    type: 'warning',
                })
            }
        },
        change: (i) => {
            console.log(i)
            const obj = i.options.find((ele) => {
                return ele.id === i.value
            })
            console.log(obj)
            if (obj) {
                i.value1 = obj.userName
                i.tbtade = dayjs(obj.insurStartTime).format('YYYY-MM-DD')
                formData.value.caseDate.value = dayjs(obj.insurStartTime).format(
                    'YYYY-MM-DD'
                )
            } else {
                i.value1 = ''
                i.tbtade = ''
            }
        },
    },
    phone: {
        label: '出险人手机号',
        type: 'input',
        prop: 'phone',
        placeholder: '请输入手机号',
        value: '',
        width: 'half',
    },
    caseDate: {
        label: '出险时间',
        type: 'date',
        dateType: 'datetime',
        prop: 'caseDate',
        placeholder: '请选择出险时间',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        format: 'YYYY-MM-DD HH:mm:ss',
        value: '',
        disabledDate: (time) => {
            return (
                time.getTime() <= new Date(formData.value.people.tbtade).getTime() ||
                time.getTime() > new Date().getTime()
            )
        },
        width: 'half',
        focus: (i) => {
            if (!formData.value.people.value) {
                ElMessage({
                    message: '请先选择出险人',
                    type: 'warning',
                })
            }
        },
    },
    caseType: {
        label: '事故类型',
        type: 'select',
        prop: 'caseType',
        placeholder: '请选择事故类型',
        value: '',
        options: [
            { label: '工伤', value: 2 },
            { label: '意外', value: 1 },
        ],
        defaultAttrs: {
            label: 'label',
            value: 'value',
        },
        width: 'half',
    },
    isDangerous: {
        label: '是否有骨折或更严重伤情',
        type: 'select',
        prop: 'isDangerous',
        placeholder: '请选择',
        value: '',
        options: [
            { label: '是', value: 1 },
            { label: '不是', value: 2 },
        ],
        defaultAttrs: {
            label: 'label',
            value: 'value',
        },
        width: 'half',
    },
    hospitalStatus: {
        label: '是否住院',
        type: 'select',
        prop: 'hospitalStatus',
        placeholder: '请选择',
        value: '',
        options: [
            { label: '是', value: 1 },
            { label: '不是', value: 2 },
        ],
        defaultAttrs: {
            label: 'label',
            value: 'value',
        },
        width: 'half',
    },
    location: {
        label: '出现地点',
        type: 'input',
        prop: 'location',
        placeholder: '请输入出险地点，如xx公司xx车间',
        value: '',
        width: 'full',
    },
    hospital: {
        label: '就诊医院',
        type: 'input',
        prop: 'hospital',
        placeholder: '如：昆山市第一人民医院',
        value: '',
        width: 'full',
    },
    description: {
        label: '详细事故经过',
        type: 'textarea',
        prop: 'description',
        placeholder: '请输入详细事故经过',
        value: '',
        width: 'full',
    },
    reportPhone: {
        label: '报案人电话',
        type: 'input',
        prop: 'reportPhone',
        placeholder: '请输入报案人电话',
        value: '',
        width: 'full',
    },
})
const submit = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            console.log(formData.value.videos, 'sghufguysuy')
            reportlongcaseapi({
                companyId: formData.value.company.value,
                outDangerUserName: formData.value.people.value1,
                outDangerPhone: formData.value.phone.value,
                outDangerDate: formData.value.caseDate.value,
                accidentType: formData.value.caseType.value,
                hurtStatus: formData.value.isDangerous.value,
                hospitalStatus: formData.value.hospitalStatus.value,
                outDangerPlace: formData.value.location.value,
                visitHospital: formData.value.hospital.value,
                accidentDetails: formData.value.description.value,
                reportPhone: formData.value.reportPhone.value,
                isAdmin: 1,
                recordId: formData.value.people.value,
                params: {
                    photos: formData.value.videos.value || [],
                },
            }).then((res) => {
                ElMessage({
                    message: '操作成功',
                    type: 'success',
                })
                handleClose()
            })
        } else {
            console.log('error', fields)
        }
    })
}
const rules = ref({
    'company.value': [
        {
            required: true,
            trigger: 'change',
            message: '请输入报案公司名称',
        },
    ],
    'people.value': [
        {
            required: true,
            trigger: 'change',
            message: '出险人不能为空',
        },
    ],
    'phone.value': [
        {
            required: true,
            trigger: 'change',
            message: '出险人手机号不能为空',
        },
    ],
    'caseDate.value': [
        {
            required: true,
            trigger: 'change',
            message: '出险时间不能为空',
        },
    ],
    'caseType.value': [
        {
            required: true,
            trigger: 'change',
            message: '事故类型不能为空',
        },
    ],
    'isDangerous.value': [
        {
            required: true,
            trigger: 'change',
            message: '是否有骨折或更严重伤情不能为空',
        },
    ],
    'hospitalStatus.value': [
        {
            required: true,
            trigger: 'change',
            message: '是否住院不能为空',
        },
    ],
    'location.value': [
        {
            required: true,
            trigger: 'change',
            message: '出现地点不能为空',
        },
    ],
    'hospital.value': [
        {
            required: true,
            trigger: 'change',
            message: '就诊医院不能为空',
        },
    ],
    'description.value': [
        {
            required: true,
            trigger: 'change',
            message: '详细事故经过不能为空',
        },
    ],
    'reportPhone.value': [
        {
            required: true,
            trigger: 'change',
            message: '报案人电话不能为空',
        },
    ],
})

const handleClose = () => {
    resetForm(formRef.value)
    dialogVisible.value = false
    formData.value.people.options = []
    formData.value.company.options = []
}

watch(
    () => props.show,
    (newval) => {
        dialogVisible.value = newval
        if (newval) {
            // resetForm(formRef.value);
        }
    }
)

watch(dialogVisible, (newval) => {
    emits('update:show', newval)
    if (!newval) {
        // formRef.value.resetFields()
    }
})
</script>
<style lang="scss" scoped>
.header {
    &::before {
        content: "";
        border-left: 4px solid #0256ff;
        height: 14px;
        margin-right: 5px;
    }
}

.grid {
    display: flex;
    flex-wrap: wrap;
}
.full {
    flex-basis: calc(100% - 10px);
}
.half {
    flex-basis: calc(50% - 10px);
}

:deep(.reset-date .el-input__wrapper) {
    // display: flex;
    width: calc(100% - 20px) !important;
}

:deep(.reset-card .el-upload--picture-card) {
    justify-content: start;
    background: #fff;
}

:deep(.reset-card .el-upload-list__item) {
    width: 72px;
    height: 72px;
}

:deep(.reset .el-drawer__header) {
    margin-bottom: 0;
}
</style>
